package com.lagou.edu.controller;

import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.LagouAuthCodeService;
import com.lagou.edu.utils.FormatVaildate;
import com.lagou.edu.utils.MyDateTime;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/email")
@RestController
public class EmailController {

    @Reference
    private LagouAuthCodeService lagouAuthCodeService;


    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送验证码到邮箱，true成功，false失败
     * @param email
     * @param code
     * @return
     */
    @RequestMapping("/email/{email}/{code}")
    public Boolean email(@PathVariable("email") String email,
                         @PathVariable("code") String code){

        if (!FormatVaildate.isEmail(email)){
            return false;
        }
        //先删掉历史记录
        lagouAuthCodeService.removeByEmail(email);
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(MyDateTime.getCurrentDateTime());
        lagouAuthCode.setExpiretime(MyDateTime.getAfterTenMinute());
        LagouAuthCode save = lagouAuthCodeService.save(lagouAuthCode);
        if (save.getId() != null){
            //去发邮件将验证码发送到传入的邮箱
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(email);
            message.setSubject("注册账号验证码");
            message.setText(code);
            javaMailSender.send(message);
        }
        return true;
    }
}
